package com.yanyeori.framework.datasource.config;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态数据源
 *
 * @author chenkuan 2020/8/6
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static volatile DynamicDataSource instance;

    private Map<Object, Object> targetDataSources = new HashMap<>();
    private Object defaultTargetDataSource;
    private Map<String, List<String>> primarySlaveDbMap = new HashMap<>();

    private DynamicDataSource() {
    }

    /**
     * 获取DynamicDataSource单例
     */
    public static DynamicDataSource getInstance() {
        if (instance == null) {
            synchronized (DynamicDataSource.class) {
                if (instance == null) {
                    instance = new DynamicDataSource();
                }
            }
        }
        return instance;
    }

    /**
     * 返回当前数据源key，然后动态切换
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return DatabaseContextHolder.getDBKey();
    }

    public Map<Object, Object> getTargetDataSources() {
        return targetDataSources;
    }

    /**
     * 用来动态创建数据源
     */
    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        this.targetDataSources = targetDataSources;
    }

    public Object getDefaultTargetDataSource() {
        return defaultTargetDataSource;
    }

    /**
     * 设置默认数据源
     */
    public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        this.defaultTargetDataSource = defaultTargetDataSource;
    }

    public Map<String, List<String>> getPrimarySlaveDbMap() {
        return primarySlaveDbMap;
    }

    public void setPrimarySlaveDbMap(Map<String, List<String>> primarySlaveDbMap) {
        this.primarySlaveDbMap = primarySlaveDbMap;
    }
}
